<?php

namespace app\api\facade;

use app\api\service\JwtService;
use support\Request;

/**
 * JWT门面类
 * @method static string generateToken(array $payload, int $ttl = 3600)
 * @method static array verifyToken(string $token)
 * @method static string getTokenFromHeader()
 * @method static int getUserId()
 * @method static array getCurrentUser()
 * @method static string refreshToken(array $payload, int $ttl = 3600)
 * @method static int getTokenTTL(string $token)
 * @method static JwtService setRequest(Request $request)
 * @method static array getConfig()
 */
class Jwt
{
    /**
     * @var JwtService 服务实例
     */
    protected static JwtService $service;

    /**
     * 获取服务实例
     * @return JwtService
     */
    protected static function getService(): JwtService
    {
        if (!isset(self::$service)) {
            self::$service = new JwtService();
        }
        return self::$service;
    }

    /**
     * 静态调用服务方法
     * @param string $name
     * @param array $arguments
     * @return mixed
     */
    public static function __callStatic(string $name, array $arguments)
    {
        $service = self::getService();
        return $service->$name(...$arguments);
    }

    /**
     * 生成JWT令牌
     * @param array $payload
     * @param int $ttl
     * @return string
     */
    public static function generateToken(array $payload, int $ttl = 3600): string
    {
        return self::getService()->generateToken($payload, $ttl);
    }

    /**
     * 验证JWT令牌
     * @param string $token
     * @return array
     */
    public static function verifyToken(string $token): array
    {
        return self::getService()->verifyToken($token);
    }

    /**
     * 从请求头获取令牌
     * @return string
     */
    public static function getTokenFromHeader(): string
    {
        return self::getService()->getTokenFromHeader();
    }

    /**
     * 获取用户ID
     * @return int
     */
    public static function getUserId(): int
    {
        return self::getService()->getUserId();
    }

    /**
     * 获取当前用户信息
     * @return array
     */
    public static function getCurrentUser(): array
    {
        return self::getService()->getCurrentUser();
    }

    /**
     * 刷新令牌
     * @param array $payload
     * @param int $ttl
     * @return string
     */
    public static function refreshToken(array $payload, int $ttl = 3600): string
    {
        return self::getService()->refreshToken($payload, $ttl);
    }

    /**
     * 获取令牌剩余有效期
     * @param string $token
     * @return int
     */
    public static function getTokenTTL(string $token): int
    {
        return self::getService()->getTokenTTL($token);
    }
}